const express = require('express');
const cors = require('cors');
const compression = require('compression');
const session = require('express-session');
const RedisStore = require('connect-redis').default;
const { errorHandler, notFound } = require('./middleware/errorMiddleware');
const securityMiddleware = require('./middleware/securityMiddleware');
const logger = require('./utils/logger');
const { config, validateConfig } = require('./config/config');
const { connectDB } = require('./config/database');
const { cacheManager } = require('./utils/cache');
const { schedulerManager } = require('./utils/scheduler');

// 验证配置
validateConfig();

const app = express();
const PORT = config.app.port;

// 安全中间件
app.use(securityMiddleware.helmet);
app.use(securityMiddleware.customSecurity);
app.use(securityMiddleware.sanitize);
app.use(securityMiddleware.xss);
app.use(securityMiddleware.hpp);
app.use(securityMiddleware.requestSizeLimit);
app.use(securityMiddleware.apiVersionCheck);
app.use(securityMiddleware.requestLogger);

// CORS配置
app.use(cors({
  origin: config.app.frontendUrl,
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-API-Version']
}));

// 会话配置
const sessionConfig = {
  store: new RedisStore({ client: cacheManager.client }),
  secret: config.session.secret,
  name: config.session.name,
  cookie: config.session.cookie,
  resave: false,
  saveUninitialized: false
};
app.use(session(sessionConfig));

// 基础中间件
app.use(compression());

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 速率限制
app.use('/api/', securityMiddleware.rateLimit);
app.use('/api/auth/login', securityMiddleware.loginRateLimit);

// 健康检查
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'OK',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    environment: config.app.env,
    version: config.app.version
  });
});

// API信息
app.get('/api/info', (req, res) => {
  res.json({
    name: config.app.name,
    description: config.app.description,
    version: config.app.version,
    environment: config.app.env
  });
});

// API路由
app.use('/api/auth', require('./routes/authRoutes'));
app.use('/api/users', require('./routes/userRoutes'));

// 错误处理中间件
app.use(notFound);
app.use(errorHandler);

// 启动服务器
const startServer = async () => {
  try {
    // 尝试连接数据库
    try {
      await connectDB();
      logger.info('✅ 数据库连接成功');
    } catch (dbError) {
      logger.warn('⚠️ 数据库连接失败，应用程序将在有限模式下运行:', dbError.message);
      logger.warn('请确保MySQL服务正在运行，并且配置正确');
    }

    // 尝试连接Redis缓存
    try {
      await cacheManager.connect();
      logger.info('✅ Redis缓存连接成功');
    } catch (redisError) {
      logger.warn('⚠️ Redis缓存连接失败，将使用内存会话存储:', redisError.message);
      // 修改会话配置为内存存储
      sessionConfig.store = undefined;
    }

    // 初始化任务调度器（仅在数据库连接成功时）
    if (config.scheduler.enableScheduledTasks) {
      try {
        schedulerManager.createCleanupTask();
        schedulerManager.createHealthCheckTask();
        schedulerManager.createBackupTask();
        schedulerManager.startAllTasks();
        logger.info('✅ 任务调度器启动成功');
      } catch (schedulerError) {
        logger.warn('⚠️ 任务调度器启动失败:', schedulerError.message);
      }
    }

    app.listen(PORT, () => {
      logger.info(`🚀 服务器启动成功，端口: ${PORT}`);
      logger.info(`🌍 环境: ${config.app.env}`);
      logger.info(`📦 版本: ${config.app.version}`);
      logger.info(`🔗 前端地址: ${config.app.frontendUrl}`);
      logger.info(`📊 健康检查: http://localhost:${PORT}/health`);
      logger.info(`📋 API信息: http://localhost:${PORT}/api/info`);
    });
  } catch (error) {
    logger.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
};

// 优雅关闭
const gracefulShutdown = async (signal) => {
  logger.info(`收到信号 ${signal}，开始优雅关闭`);

  try {
    // 停止任务调度器
    if (config.scheduler.enableScheduledTasks) {
      schedulerManager.stopAllTasks();
    }

    // 断开缓存连接
    await cacheManager.disconnect();

    logger.info('优雅关闭完成');
    process.exit(0);
  } catch (error) {
    logger.error('优雅关闭失败:', error);
    process.exit(1);
  }
};

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

// 未捕获的异常处理
process.on('uncaughtException', (error) => {
  logger.error('未捕获的异常:', error);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('未处理的Promise拒绝:', reason);
  process.exit(1);
});

startServer();

module.exports = app;
